const fs = require("fs");
const path = require("path");
const formatDate = require("../../tools/formatDate")

module.exports = (req, res) => {

    let { findPath } = req.query;

    fs.readdir(findPath, (err, files) => {

        if (err) {
            console.log(err);
            return res.send({
                code: 400,
                result: [],
                msg: "读取路径出错！"
            })
        };

        // 存放文件夹路径
        let dirArr = [];
        // 存放文件
        let fileArr = [];

        try {
            for (let i = 0; i < files.length; i++) {
                let _path = path.resolve(findPath, files[i]);
                let item = fs.statSync(_path);

                if (item.isDirectory()) {
                    // 是文件夹
                    dirArr.push(_path);
                } else if (/\.(mp4|avi|wmv|flv|ts|webm)$/.test(_path)) {
                    // 是文件
                    fileArr.push({
                        filename: _path,
                        filesize: (item.size / 1024 / 1024).toFixed(1) + 'm',
                        createTime: formatDate(item.birthtime),
                        state: '未转换'
                    });
                }
            }
        } catch (error) {
            return res.send({
                code: 400,
                result: [],
                msg: "读取路径出错！"
            })
        }


        res.send({
            code: 200,
            msg: "检索成功！",
            result: fileArr,
            dirs: dirArr
        })
    });

}